import request from "@/utils/request";
import { Modal, message } from "antd";
import { cloneDeep, indexOf, find, union, remove } from "lodash";
import moment from "moment";
import { stringify } from "qs";
import { removeAll } from './authority';

//校验菜单是否存在
const checkRoute = (path, list) => {
	//获取菜单信息的递归函数
	if (path == "/") {
		return true;
	}
	let btn = false;
	for (let i in list) {
		if (list[i].path == "/") {
			continue;
		}
		const re = new RegExp("^(" + list[i].path + ")/");
		if (list[i].path == path || re.test(path)) {
			if (list[i].path && list[i].path == path) {
				btn = true;
				break;
			} else {
				//如果有子菜单，二级菜单
				btn = checkRoute(path, list[i].children);
			}
		}
	}
	return btn;
};

/**
 * desc: 验证当前页面权限
 * @param {string} path 当前页面路径
 * @param {array} route1 服务端返回权限路由
 */
export const getPathAuthority = (path, route1) => {
	const authority = checkRoute(path, route1);
	if (authority) {
		//当前页面有权限
		return 1;
	} else {
		//当前页面没有权限
		return 2;
	}
};

/**
 * @desc 下载文件
 * @param {blob} blob 下载的对象内容
 * @param {string} fileName  下载文件名
 */
export const downLoad = (blob, fileName) => {
	const a = document.createElement("a");
	const url = window.URL.createObjectURL(blob);
	const filename = fileName;
	a.href = url;
	a.download = filename;
	a.click();
	//此处有一个疑问，a标签需不需要手动移除
	window.URL.revokeObjectURL(url);
};

/**
 * @desc 点击下载excel文件处理事件
 * @param {string} url 导出地址
 * @param {string} fileName 文件名称，不传为默认值
 * @param {function} cb  回调函数，用于处理loading等事件
 */
export const handleExportExcel = async (url, fileName = "用户数据.xlsx", cb) => {
	request(url, {
		getResponse: true,
		responseType: "blob"
	}).then(({ data }) => {
		if (data) {
			downLoad(data, fileName);
		}
		cb && cb();
	});
};

/**
 * @desc 点击下载excel文件处理事件
 * @param {string} url 导出地址
 * @param {params} params 参数
 * @param {string} fileName 文件名称，不传为默认值
 * @param {function} cb  回调函数，用于处理loading等事件
 */
export const handleExportExcel2 = async (url, params, fileName = "用户数据.xlsx", cb) => {
	request(url, {
		method: "POST",
		data: params,
		getResponse: true,
		responseType: "blob"
	}).then(({ data }) => {
		if (data) {
			downLoad(data, fileName);
		}
		cb && cb();
	});
};

//店铺授权回调展示
export const handleAuthorize = (location, navigate) => {
	const obj = getSearchParamsObj(location.search);
	if (obj.authState && obj.msg) {
		navigate("/shop/mine");
		if (obj.authState == 1) {
			//授权成功回调
			Modal.success({
				title: "授权成功",
				content: (
					<div>
						<p>
							1、授权成功，授权时间 {moment(Date.now()).format("YYYY-MM-DD HH:mm:ss")}，有效期至{" "}
							{moment(obj.msg * 1000).format("YYYY-MM-DD HH:mm:ss")}
						</p>
						<p>2、授权内容：同步店铺商品，同步店铺订单</p>
					</div>
				)
			});
		} else {
			Modal.error({
				title: "授权失败",
				content: (
					<div>
						<p className="textOverflowMulti">错误信息：{obj.msg}</p>
						<p>如有疑问，请联系客服</p>
					</div>
				)
			});
		}
	}
};

// 金额每三位增加一个逗号
export const addCommas = nStr => {
	nStr += "";
	const x = nStr.split(".");
	let x1 = x[0];
	const x2 = x.length > 1 ? "." + x[1] : "";
	const rgx = /(\d+)(\d{3})/;
	if (rgx.test(x1)) {
		x1 = x1.replace(rgx, "$1" + "," + "$2");
	}
	return x1 + "." + Number(x2.slice(0, 3)).toFixed(2).split(".")[1];
};

/**
 * @desc 第三平台点击图片跳转商品详情公共处理函数
 * @param {*} skuId 商品skuid
 * @param {*} type 平台类型
 */
export const formatHref = (spuId, type, skuId) => {
	if (spuId && type) {
		if (type == 1) {
			//jd
			if (!skuId) {
				return null;
			}
			return `https://item.jd.com/${skuId}.html`;
		} else if (type == 8) {
			//taobao
			return `https://item.taobao.com/item.htm?id=${spuId}`;
		} else if (type == 9) {
			//pdd
			return `http://yangkeduo.com/goods.html?goods_id=${spuId}`;
		} else if (type == 4) {
			//albb
			return `https://detail.1688.com/offer/${spuId}.html`;
		} else if (type == 22) {
			//苏宁
			return `https://product.suning.com/0000000000/${spuId}.html`;
		} else {
			return null;
		}
	} else {
		return null;
	}
};

/**
 * @desc 找家纺商城图片跳转商品详情公共处理函数
 * @param {*} skuId 商品skuid
 */
export const formatZjfHref = skuId => {
	if (skuId) {
		return `http://www.zhaojiafang.com/?spm=goodsdetail.search&goods_id=${skuId}`;
	} else {
		return null;
	}
};

/**
 * @desc 第三平台图片加载压缩图公共处理函数
 * @param {string} img 原图片路径
 * @param {string|number} type 平台类型
 * @param {string} size 图片压缩大小
 * @param {string|number} width 图片宽度大小
 */
//三方平台图片暂时不展示缩略图
export const formatImg = (img, type, size, width = 48) => {
	if (img) {
		return img;
		// if (type == 1) {//jd
		//   return `${img}!cc_${size}.jpg`;
		// } else if (type == 8) {//taobao
		//   return `${img}_${size}Q50s50.jpg`;
		// } else if (type == 9) {//pdd
		//   return img;
		// } else if( type == 4) {//albb
		//   return img.replace(/.jpg/,`.${size}.jpg`);
		// } else {
		//   return img;
		// }
	} else {
		return `https://imgniu.zhaojiafang.com/no-img${width}.jpg`;
	}
};

/**
 * @desc: 找家纺平台图片加载压缩图公共处理函数
 * @param {string} img 图片原路径
 * @param {number|string} id  店铺id
 * @param {string} size 需要展示压缩图的大小，不传则为原图，目前支持48x48,64x64,84x84,如果需要其他尺寸请提出
 * @param {string|number} width 图片宽度大小
 */
export const formatZjfImg = (img, id, size, width = 48) => {
	//检测图片是否是完整路径，如果不是需要拼接
	if (!img) {
		return `https://imgniu.zhaojiafang.com/no-img${width}.jpg`;
	}
	if (/^(http|https)/.test(img)) {
		if (/zhaojiafang/.test(img)) {
			return size ? `${img}_${size}` : img;
		} else {
			return img;
		}
	} else {
		return size
			? `https://imgniu.zhaojiafang.com/store/goods/${id}/${img}_${size}`
			: `https://imgniu.zhaojiafang.com/store/goods/${id}/${img}`;
	}
};

/**
 * @desc: 处理好评卡、吊牌等图片地址为脏数据(空，非绝对路径)的问题
 * @param {string} img 图片原路径
 * @param {string|number} width 图片宽度大小
 */
export const formatCompleteImg = (img, width = 48) => {
	if (img && /^(http|https)/.test(img)) {
		return img;
	} else {
		return `https://imgniu.zhaojiafang.com/no-img${width}.jpg`;
	}
};

//处理图片同步下来携带尺寸问题
export const formatImageUrl = (str, isSuffix = false) => {
	if (!str?.length) return;
	let arr = str.split(".");
	if (arr.length > 2 && arr[arr.length - 2] == "80x80") {
		arr.splice(arr.length - 2, 1);
		str = arr.join(".");
	}
	if (arr.length > 2 && arr[arr.length - 2].includes("_30x30")) {
		arr[arr.length - 2] = arr[arr.length - 2].replace("_30x30", "");
		arr = arr.slice(0, arr.length - 1);
		str = arr.join(".");
	}
	if (isSuffix && /_[0-9]{2,4}x[0-9]{2,4}/.test(arr[arr.length - 1])) {
		arr[arr.length - 1] = arr[arr.length - 1].replace(/_[0-9]{2,4}x[0-9]{2,4}/, "");
		str = arr.join(".");
	}
	if (isSuffix && !["jpg", "png", "jpeg"].includes(arr[arr.length - 1].toLowerCase())) {
		str = str + ".jpg";
	}
	return str;
};

/**
 * @desc: 公用的图片处理方法
 * @param {string} img 图片原路径
 * @param {number|string} id  店铺id,三方平台图片不需要id；
 * @param {string} size 需要展示压缩图的大小，不传则为原图，目前支持48x48,64x64,84x84,如果需要其他尺寸请提出
 */

export const formatSysImg = (img, id, size) => {
	const width = [48, 64, 84].includes(Number(size)) && size;
	//检测图片是否是完整路径，如果不是需要拼接
	if (!img) {
		return `https://imgniu.zhaojiafang.com/no-img${width || 48}.jpg`;
	}
	if (/^(http|https)/.test(img)) {
		if (/zhaojiafang/.test(img)) {
			return width ? `${img}_${width}x${width}` : img;
		} else {
			return formatImageUrl(img);
		}
	} else {
		return width
			? `https://imgniu.zhaojiafang.com/store/goods/${id}/${img}_${width}x${width}`
			: `https://imgniu.zhaojiafang.com/store/goods/${id}/${img}`;
	}
};

//把数据转化为formdata
export const toFormData = obj => {
	const formData = new FormData();
	Object.keys(obj).forEach(v => {
		// fileList 是要上传的文件数组
		formData.append(v, obj[v]);
	});
	return formData;
};

/**
 * @desc: 金额保留两位小数
 * @param {number|string} 金额
 */
export const formatAmount = val => {
	let count;
	if (val) {
		const price = Number(val);
		if (isNaN(price)) {
			return null;
		} else {
			count = price.toFixed(2);
		}
	} else {
		if (val == 0) {
			count = "0.00";
		} else {
			return null;
		}
	}
	//金额每三位加一个逗号
	const reg = count.indexOf(".") > -1 ? /\B(?=(\d{3})+\.)/g : /\B(?=(\d{3})+$)/g;

	return `${count.replace(reg, ",")}`;
};

/**
 * @desc: 重量保留两三位小数
 * @param {number|string} 重量
 */
export const formatWeight = val => {
	if (val) {
		const weight = Number(val);
		if (isNaN(weight)) {
			return null;
		} else {
			return weight.toFixed(3);
		}
	} else {
		if (val == 0) {
			return 0;
		}
		return null;
	}
};

/**
 * @desc: 表单输入框去除前后空格（trim)
 * @param {object} 表单参数
 */
export const customTrimFunc = obj => {
	const params = cloneDeep(obj);
	if (params && Object.prototype.toString.call(params) === "[object Object]") {
		const arr = Object.keys(params);
		if (arr.length) {
			for (let i = 0; i < arr.length; i++) {
				if (typeof params[arr[i]] == "string") {
					params[arr[i]] = params[arr[i]].trim() ? params[arr[i]].trim() : undefined;
				}
			}
			return params;
		} else {
			return {};
		}
	} else {
		return {};
	}
};

/**
 * @desc: 跳转url
 * @param {*} url,如果有就跳转，没有就忽略
 */
export const openUrl = url => {
	if (url) {
		window.open(url);
	} else {
		return false;
	}
};

/**
 * @desc: 展示sku+spu名称，京东的特殊需要单独处理
 * @param {*} type,平台类型
 * @param {*} skuName,
 * @param {*} spuName,
 *
 */
export const renderGoodsName = (type, spuName, skuName) => {
	if (type == 1) {
		//jd的商品
		return skuName || spuName;
	} else {
		return skuName ? `${spuName} ${skuName}` : spuName;
	}
};

//根据url设置不同的权限类型
export const renderRoleType = () => {
	const hostName = window.location.hostname;
	if (hostName.includes("test2")) {
		if (hostName == "daifa.test2.zhaojiafang.com") {
			return "daifa"; //代发用户
		} else if (hostName == "zifa.test2.zhaojiafang.com") {
			return "zifa"; //代发用户
		} else if (hostName == "o.test2.zhaojiafang.com") {
			return "erp"; //erp用户
		} else {
			return "zjf"; //所有用户
		}
	} else if (hostName.includes("test1")) {
		if (hostName == "daifa.test1.zhaojiafang.com") {
			return "daifa"; //代发用户
		} else if (hostName == "zifa.test1.zhaojiafang.com") {
			return "zifa"; //代发用户
		} else if (hostName == "o.test1.zhaojiafang.com") {
			return "erp"; //erp用户
		} else {
			return "zjf"; //所有用户
		}
	} else if (hostName.includes("test3")) {
		if (hostName == "daifa.test3.zhaojiafang.com") {
			return "daifa"; //代发用户
		} else if (hostName == "zifa.test3.zhaojiafang.com") {
			return "zifa"; //代发用户
		} else if (hostName == "o.test3.zhaojiafang.com") {
			return "erp"; //erp用户
		} else {
			return "zjf"; //所有用户
		}
	} else if (hostName.includes("stage")) {
		if (hostName == "daifa.stage.zhaojiafang.com") {
			return "daifa"; //代发用户
		} else if (hostName == "zifa.stage.zhaojiafang.com") {
			return "zifa"; //代发用户
		} else if (hostName == "o.stage.zhaojiafang.com") {
			return "erp"; //erp用户
		} else {
			return "zjf"; //所有用户
		}
	} else {
		if (hostName == "daifa.zhaojiafang.com") {
			return "daifa"; //代发用户
		} else if (hostName == "zifa.zhaojiafang.com") {
			return "zifa"; //代发用户
		} else if (hostName == "o.zhaojiafang.com") {
			return "erp"; //erp用户
		} else {
			return "zjf"; //所有用户
		}
	}
};

/**
 * @desc: 页面数据局部刷新操作函数
 * @param oldData 原列表中的数据
 * @param idsData 通过ids字段 接口查询到的数据
 * @param id id字段名
 * @param type 1替换 2删除
 */
export const handlePartRefresh = (oldData, idsData, id = "id", type = 1) => {
	const idsArr = cloneDeep(idsData).map(item => {
		return item[id];
	});
	const newData = [];
	oldData.map(item => {
		if (type == 1) {
			if (indexOf(idsArr, item[id]) == -1) {
				newData.push(item);
			} else {
				newData.push(find(idsData, [id, item[id]]));
			}
		} else if (type == 2) {
			if (indexOf(idsArr, item[id]) == -1) {
				newData.push(item);
			}
		}
	});
	return newData;
};

//渲染不同的快递类型
export const handleRenderExpressTag = (type = "5", name) => {
	if (type == 1) {
		return (
			<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
				<span className="text-overflow" style={{ flex: 1 }}>
					{name}
				</span>
				<span
					style={{
						width: "20px",
						height: "20px",
						lineHeight: "20px",
						borderRadius: "50%",
						backgroundImage: "linear-gradient(45deg, #0071F0, #5AA9FF)",
						color: "#fff",
						textAlign: "center",
						fontSize: "12px"
					}}
				>
					找
				</span>
			</div>
		);
	} else if (type == 2) {
		return (
			<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
				<span className="text-overflow" style={{ flex: 1 }}>
					{name}
				</span>
				<span
					style={{
						width: "20px",
						height: "20px",
						lineHeight: "20px",
						borderRadius: "50%",
						backgroundImage: "linear-gradient(45deg, #981FDD, #CE6FFF)",
						color: "#fff",
						textAlign: "center",
						fontSize: "12px"
					}}
				>
					仓
				</span>
			</div>
		);
	} else if (type == 3) {
		return (
			<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
				<span className="text-overflow" style={{ flex: 1 }}>
					{name}
				</span>
				<span
					style={{
						width: "20px",
						height: "20px",
						lineHeight: "20px",
						borderRadius: "50%",
						backgroundImage: "linear-gradient(45deg, #FF9000, #FFD285)",
						color: "#fff",
						textAlign: "center",
						fontSize: "12px"
					}}
				>
					用
				</span>
			</div>
		);
	} else if (type == 4) {
		return (
			<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
				<span className="text-overflow" style={{ flex: 1 }}>
					{name}
				</span>
				<span
					style={{
						width: "20px",
						height: "20px",
						lineHeight: "20px",
						borderRadius: "50%",
						backgroundImage: "linear-gradient(45deg, #1DC11D, #1DC11D)",
						color: "#fff",
						textAlign: "center",
						fontSize: "12px"
					}}
				>
					厂
				</span>
			</div>
		);
	} else {
		return <span>{name}</span>;
	}
};

//快递渲染及tag标识(临近布局)
export const renderExpressAndTag = (type = "4", name, style = {}) => {
	const styleObj = {
		display: "inline-block",
		width: "20px",
		height: "20px",
		lineHeight: "20px",
		borderRadius: "50%",
		color: "#fff",
		textAlign: "center",
		fontSize: "12px",
		marginLeft: "6px",
		...style
	};
	if (type == 1) {
		return (
			<div style={{ display: "flex", alignItems: "center" }}>
				<div>
					<span>{name}</span>
					<span style={{ ...styleObj, backgroundImage: "linear-gradient(45deg, #0071F0, #5AA9FF)" }}>找</span>
				</div>
			</div>
		);
	} else if (type == 2) {
		return (
			<div style={{ display: "flex", alignItems: "center" }}>
				<div>
					<span>{name}</span>
					<span style={{ ...styleObj, backgroundImage: "linear-gradient(45deg, #981FDD, #CE6FFF)" }}>仓</span>
				</div>
			</div>
		);
	} else if (type == 3) {
		return (
			<div style={{ display: "flex", alignItems: "center" }}>
				<div>
					<span>{name}</span>
					<span style={{ ...styleObj, backgroundImage: "linear-gradient(45deg, #FF9000, #FFD285)" }}>用</span>
				</div>
			</div>
		);
	} else {
		return <span>{name}</span>;
	}
};

//找，用，倉的渲染
export const renderChannelIcon = (logisticsUuid, uuid) => {
	const commonIconStyle = {
		display: "inline-block",
		marginLeft: "4px",
		width: "20px",
		height: "20px",
		lineHeight: "20px",
		borderRadius: "50%",
		color: "#fff",
		textAlign: "center",
		fontSize: "12px"
	};
	if (logisticsUuid == -1 || logisticsUuid == -2 || logisticsUuid == -3) {
		return null;
	} else if (logisticsUuid == 1) {
		return (
			<span
				style={{
					...commonIconStyle,
					backgroundImage: "linear-gradient(45deg, #0071F0, #5AA9FF)"
				}}
			>
				找
			</span>
		);
	} else {
		if (logisticsUuid == uuid) {
			return (
				<span
					style={{
						...commonIconStyle,
						backgroundImage: "linear-gradient(45deg, #FF9000, #FFD285)"
					}}
				>
					用
				</span>
			);
		} else {
			return (
				<span
					style={{
						...commonIconStyle,
						backgroundImage: "linear-gradient(45deg, #981FDD, #CE6FFF)"
					}}
				>
					仓
				</span>
			);
		}
	}
};

//一写公共的计算方法（为了消除浮点数）
//加法
/**
 *
 * @param {*} a 数字
 * @param {*} b 数字
 * @param {*} count 保留小数位数，默认两个
 * @returns
 */
export const commonAdd = (a, b, count = 2) => {
	let c, d, e;
	try {
		c = a.toString().split(".")[1].length;
	} catch (f) {
		c = 0;
	}
	try {
		d = b.toString().split(".")[1].length;
	} catch (f) {
		d = 0;
	}
	e = Math.pow(10, Math.max(c, d));
	return commonMul(a, e) + commonMul(b, e) / e.toFixed(2);
};

//减法
export const commonSub = (a, b, count = 2) => {
	let c, d, e;
	try {
		c = a.toString().split(".")[1].length;
	} catch (f) {
		c = 0;
	}
	try {
		d = b.toString().split(".")[1].length;
	} catch (f) {
		d = 0;
	}
	e = Math.pow(10, Math.max(c, d));
	return (commonMul(a, e) - commonMul(b, e)) / e.toFixed(count);
};

//乘法
export const commonMul = (a, b, count = 2) => {
	let c = 0,
		d = a.toString(),
		e = b.toString();
	try {
		c += d.split(".")[1].length;
	} catch (f) {}
	try {
		c += e.split(".")[1].length;
	} catch (f) {}
	return ((Number(d.replace(".", "")) * Number(e.replace(".", ""))) / Math.pow(10, c)).toFixed(count);
};

//除法
export const commonDiv = (a, b, count = 2) => {
	let c,
		d,
		e = 0,
		f = 0;
	try {
		e = a.toString().split(".")[1].length;
	} catch (g) {}
	try {
		f = b.toString().split(".")[1].length;
	} catch (g) {}
	c = Number(a.toString().replace(".", ""));
	d = Number(b.toString().replace(".", ""));
	return commonMul(c / d, Math.pow(10, f - e)).toFixed(count);
};

//判断用户是否可以展示采购库存信息
export const isRenderPeriod = uuid => {
	if (!uuid) {
		return false;
	}
	if (
		[
			"erp.test1.zhaojiafang.com",
			"erp.test2.zhaojiafang.com",
			"localhost:8000",
			"localhost:8001",
			"erp.test3.zhaojiafang.com",
			"erp.stage.zhaojiafang.com",
			"o.zhaojiafang.com",
			"all.zhaojiafang.com"
		].includes(window.location.host)
	) {
		return true;
	} else {
		//前三个是用户的号，后面的是测试的账号uid；最后一个是露娜的号
		const arr = [350016, 3186, 385524, 9025, 350091, 387917, 374793, 294307, 284416];
		if (arr.includes(uuid)) {
			return true;
		} else {
			return false;
		}
	}
};

//判断某个数组中是否包含另一个数组
export const isContained = (a, b) => {
	if (!(a instanceof Array) || !(b instanceof Array)) return false;
	if (a.length < b.length || b.length == 0) return false;
	var aStr = a.toString();
	for (var i = 0, len = b.length; i < len; i++) {
		if (aStr.indexOf(b[i]) == -1) return false;
	}
	return true;
};

//前端导出excel
export const excelExport = ({
	dataSource = [], //导出的data数据
	titles = [], //标题
	fileName = "data", //导出文件名称
	suffix = "csv" //导出格式默认为csv,兼容性比较好(xslx、xls可选)
}) => {
	var dataType = "\uFEFF"; //解决乱码问题
	dataType += titles.join(","); //添加表格的头
	dataType += "\n"; // 以上是导出的Excel文件头部

	// 从dataSource中取出数据存入数据源（dataType）
	dataSource.map(item => {
		for (var v in item) {
			item[v] = item[v] ? "\t" + item[v].replace(/,/g, "，").replace(/\n/g, "，").toString() : item[v];
		} //处理特殊数据(科学计数法,英文逗号，\n)
		dataType += `${item.join(",")}\n`;
	});

	// 使用Blob，获得二进制实例
	const csvData = new Blob([dataType], {
		type: "text/csv"
	});

	// 创建a标签
	const _a = document.createElement("a");
	/**
	 * URL.createObjectURL() 静态方法会创建一个 DOMString，其中包含一个表示参数中给出的对象的URL
	 * 这里相当于为a标签添加了一个下载地址
	 */
	_a.href = URL.createObjectURL(csvData);
	// 该a标签点击后会打开新的标签页，人机交互会更加舒适
	_a.target = "_blank";
	// 为a标签规定被下载的超链接目标
	_a.download = `${fileName}.${suffix}`;
	// 将这个制作好的a标签置入body，并在点击之后移除，降低外界感知
	document.body.appendChild(_a);
	_a.click();
	document.body.removeChild(_a);
};

//获取haomi和px换算比率
export const getPxMm = () => {
	const el = document.createElement("div");
	el.id = "custom_px_mm";
	el.style.width = "1mm";
	const ele = document.querySelector("body");
	ele.appendChild(el);
	const div = document.getElementById("custom_px_mm");
	let ratio;
	try {
		ratio = div.getBoundingClientRect().width;
	} catch (error) {
		ratio = 3.8;
	}
	ele.removeChild(div);
	return ratio;
};

//多维数组的排列组合
export const doExchange = arr => {
	var len = arr.length;
	// 当数组大于等于2个的时候
	if (len >= 2) {
		// 第一个数组的长度
		var len1 = arr[0].length;
		// 第二个数组的长度
		var len2 = arr[1].length;
		// 2个数组产生的组合数
		var lenBoth = len1 * len2;
		//  申明一个新数组,做数据暂存
		var items = new Array(lenBoth);
		// 申明新数组的索引
		var index = 0;
		// 2层嵌套循环,将组合放到新数组中
		for (var i = 0; i < len1; i++) {
			for (var j = 0; j < len2; j++) {
				items[index] = [].concat(arr[0][i]).concat(arr[1][j]);
				index++;
			}
		}
		// 将新组合的数组并到原数组中
		var newArr = new Array(len - 1);
		for (var i = 2; i < arr.length; i++) {
			newArr[i - 1] = arr[i];
		}
		newArr[0] = items;
		// 执行回调
		return doExchange(newArr);
	} else {
		return arr[0];
	}
};

//根据项目链接的http或https去匹配
export const httpChange = server => {
	let newServer = "";
	if (server) {
		newServer = server.replace(/http:|https:/, `${window.location.protocol}`);
		return newServer;
	} else {
		return server;
	}
};

//只提取汉字
export const GetChinese = strValue => {
	if (strValue != null && strValue != "") {
		var reg = /[\u4e00-\u9fa5]/g;
		return strValue.match(reg).join("");
	} else return "导出记录";
};

/**
 * @description 文字转语音方法
 * @public
 * @param { text, rate, lang, volume, pitch } object
 * @param  text 要合成的文字内容，字符串
 * @param  rate 读取文字的语速 0.1~10  正常1
 * @param  lang 读取文字时的语言
 * @param  volume  读取时声音的音量 0~1  正常1
 * @param  pitch  读取时声音的音高 0~2  正常1
 * @returns SpeechSynthesisUtterance
 */
export const speak = ({ text, speechRate, lang, volume, pitch }, endEvent, startEvent) => {
	if (!window.SpeechSynthesisUtterance) {
		console.warn("当前浏览器不支持文字转语音服务");
		return;
	}

	if (!text) {
		return;
	}

	const speechUtterance = new SpeechSynthesisUtterance();
	speechUtterance.text = text;
	speechUtterance.rate = speechRate || 1;
	speechUtterance.lang = lang || "zh-CN";
	speechUtterance.volume = volume || 1;
	speechUtterance.pitch = pitch || 1;
	speechUtterance.onend = function () {
		endEvent && endEvent();
	};
	speechUtterance.onstart = function () {
		startEvent && startEvent();
	};
	speechSynthesis.speak(speechUtterance);

	return speechUtterance;
};

//关键信息脱敏(添加*****)
export const dataDesensitization = str => {
	if (str) {
		if (str.length > 2) {
			return str.substr(0, 2) + "****" + str.substr(str.length - 2);
		} else {
			return str.substr(0, 2) + "****";
		}
	}
};

//身份证信息脱敏(添加*****)
export const IdCardDesensitization = str => {
	if (str) {
		return str.substr(0, 2) + "**************" + str.substr(str.length - 2);
	}
};

//加载脚本
export async function loadScript(url) {
	const script = document.createElement("script");
	script.setAttribute("type", "text/javascript");
	script.setAttribute("src", url);
	script.setAttribute("charset", "utf-8");
	const task = new Promise(resolve => {
		script.onload = resolve;
		script.onerror = resolve;
	});
	document.body.appendChild(script);
	return task;
}

export const commonExportForPage = ({ total, size = 10000, params = {}, url, name = "表格导出", method = "get" }) => {
	if (total) {
		params.size = size;
		const nums = Math.ceil(total / 10000);
		let current = 1;
		(function exportMainCode() {
			params.current = current;
			if (method?.toLocaleLowerCase() == "get") {
				handleExportExcel(`${url}?${stringify(params)}`, `${name}.xlsx`, () => {
					current++;
					if (current <= nums) {
						exportMainCode();
					}
				});
			} else {
				handleExportExcel2(url, params, `${name}.xlsx`, () => {
					current++;
					if (current <= nums) {
						exportMainCode();
					}
				});
			}
		})();
	} else {
		message.info("暂无数据可进行导出！");
	}
};

//计算表格的滚动高度
export const handleSetHeight = (divEl, searchEl, otherHeight = 142) => {
	try {
		const sumHeight = document.getElementById("sectionContent").clientHeight;
		const searchHeight = divEl && divEl.current ? divEl.current.clientHeight : 0;
		const tableHeaderHeight = searchEl && searchEl.current ? searchEl.current.clientHeight : 0;
		// const otherHeight = 142;//表头的高度和底部分页高度再加8以及padding值等;
		const finalHeight = sumHeight - (searchHeight + tableHeaderHeight + otherHeight);
		return finalHeight;
	} catch (e) {
		console.log(e);
	}
};
export const getSearchParamsObj = search => {
	if (search && search !== "?") {
		const params = {};
		const paramArr = decodeURIComponent(search).replace(/^\?/, "").split("&");
		for (let i = 0; i < paramArr.length; i++) {
			const keyValuePair = paramArr[i].split("=");
			const key = keyValuePair[0];
			const value = keyValuePair[1] || "";
			params[key] = value;
		}
		return params;
	} else {
		return {};
	}
};

//判断是非是json字符串
export const isJSON = str => {
	if (typeof str == "string") {
		try {
			var obj = JSON.parse(str);
			if (typeof obj == "object" && obj) {
				return true;
			} else {
				return false;
			}
		} catch (e) {
			return false;
		}
	}
};

//检测非生产环境
export const testNotProdEnv = () => {
	const envList = ["localhost", "test1", "test2", "test3", "test4", "stage"],
		host = window.location.host;
	return envList.some(item => host.includes(item));
};

//聚水潭组合图标（倒数第二位）
export const convertToBinaryForJudge = num => {
	const number = new Number(num),
		str = number.toString(2);
	return str?.split("").reverse().join("").slice(1, 2) == 1;
};

//档口图标（最后一位）
export const judgeDangkouIcon = num => {
	const str = Number(num).toString(2),
		len = str?.length;
	if (len) {
		return str.slice(len - 1) == 1;
	}
};

//点击复制
export const cpText = async textToCopy => {
	// navigator clipboard 需要https等安全上下文
	if (navigator.clipboard && window.isSecureContext) {
		// navigator clipboard 向剪贴板写文本
		await navigator.clipboard
			.writeText(textToCopy)
			.then(() => {
				message.success("复制成功！");
			})
			.catch(() => {
				message.warning("复制失败");
			});
	} else {
		// 创建text area
		let textArea = document.createElement("textarea");
		textArea.value = textToCopy;
		// 使text area不在viewport，同时设置不可见
		textArea.style.position = "absolute";
		textArea.style.opacity = 0;
		textArea.style.left = "-999999px";
		textArea.style.top = "-999999px";
		document.body.appendChild(textArea);
		textArea.focus();
		textArea.select();
		return new Promise((res, rej) => {
			// 执行复制命令并移除文本框
			document.execCommand("copy") ? res() : rej();
			textArea.remove();
		})
			.then(() => {
				message.success("复制成功！");
			})
			.catch(() => {
				message.warning("复制失败");
			});
	}
};

//hiprint载入提示
export function hiprintTipsModal() {
	return Modal.info({
		title: "温馨提示",
		width: 456,
		content: (
			<div style={{ wordBreak: "break-all" }}>
				系统未检测到【hiprint】打印组件，请确保您已安装并运行该组件，如未安装，可至首页下载“hiprint“打印组件后进行安装启用，并刷新页面后重试
			</div>
		)
	});
}

//处理批量输入（统一逗号换行符，去重，判空）
export const formatBatchPrintStr = (str) => {
	if(!str) return [];
	const formatStr = str?.replace(/(,|，)+/g, '\n')?.replace(/(\w)-(\d+)-(\d+)-/g, '$1') || '';
	return union(formatStr.split('\n')).filter(item=>item.trim());
}

//当前用户无可用菜单，需要提示并抛出
export const handleResetUser = () => {
	Modal.info({
		title: '提示信息',
		content: '当前用户无权限，请联系管理员',
		okText: '确定',
		zIndex: 99999999,
		onOk: () => {
			removeAll();
			window.location.href = '#/user/login';
		}
	})
}

//获取城市选项，找家纺和纺支宝不一样
export const renderCityOptions = () => {
	if(APP_TITLE == '找家纺') {
		return [
			{ label: '南通', value: 'NT'}
		]
	} else {
		return [
			{ label: '织里', value: 'ZL'},
			{ label: '常熟', value: 'CS'}
		]
	}
}